package com.gin.no_gay_alliance.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.gin.no_gay_alliance.enums.MessageWhat;

import java.lang.ref.WeakReference;

public class MyHandler extends Handler {
    public static final String TAG = MyHandler.class.getSimpleName();
    private final WeakReference<Context> weakReference;
    private final Callback callback;

    public MyHandler(@NonNull Context context, @NonNull Callback callback) {
        super(Looper.myLooper());
        this.weakReference = new WeakReference<>(context);
        this.callback = callback;
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        Context context = weakReference.get();
        if (context != null) {
            callback.handleMessage(msg);
        } else {
            Log.w(TAG, "activity ==null");
        }
    }

    /**
     * 在Activity / Fragment的 onDestroy 方法中执行
     */
    public void onDestroy() {
        // 清空正在执行的任务
        removeCallbacksAndMessages(null);
    }

    /**
     * 发送消息
     *
     * @param what 类型
     * @param obj  obj
     */
    public void sendMessage(MessageWhat what, Object obj) {
        sendMessage(what.ordinal(), obj);
    }

    /**
     * 发送空消息
     *
     * @param what 类型
     */
    public void sendEmptyMessage(MessageWhat what) {
        sendEmptyMessage(what.ordinal());
    }

    /**
     * 发送Toast提示
     *
     * @param message 消息内容
     */
    public final void toast(String message) {
        Context context = weakReference.get();
        if (context != null) {
            Log.d(TAG, context.getClass().getSimpleName() + " toast: " + message);
            post(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT).show());
        } else {
            Log.w(TAG, "activity == null");
        }
    }

    /**
     * 发送一个"功能开发中"提示
     */
    public final void toastDevInProgress() {
        toast("功能开发中...");
    }

    /**
     * 发送长Toast提示
     *
     * @param message 消息内容
     */
    public final void toastLong(String message) {
        Context activity = weakReference.get();
        if (activity != null) {
            Log.d(TAG, activity.getClass().getSimpleName() + " toastLong: " + message);
            post(() -> Toast.makeText(activity, message, Toast.LENGTH_LONG).show());
        } else {
            Log.w(TAG, "activity ==null");
        }
    }

    /**
     * 发送消息
     *
     * @param what 类型
     * @param obj  obj
     */
    private void sendMessage(int what, Object obj) {
        sendMessage(obtainMessage(what, obj));
    }

    public interface Callback {
        /**
         * 处理消息
         *
         * @param message 消息
         * @return 是否消耗该消息
         */
        boolean handleMessage(@NonNull Message message);
    }

}